/*
** syntax_error.c for asm in /home/vanet_c//proj-kw/asm/folder_syntax
** 
** Made by charles-edouard vanet
** Login   <vanet_c@epitech.net>
** 
** Started on  Fri Dec 14 14:49:48 2012 charles-edouard vanet
** Last update Sat Dec 15 19:09:29 2012 charles-edouard vanet
*/

#include	"../../includes/asm.h"

int	verif_result(t_list **list, char c, char *str, t_my_file **my_file)
{
  int	result;

  result = 0;
  result += my_char_is_num(c);
  if (result == 0)
    return (0);
  else
    syntax_msg(list, my_file, str);
  return (1);
}

int	check_command(char *str, t_list **list, t_my_file **my_file)
{
  if (str[0] != '.')
    return (1);
  if (my_strcmp(str, NAME_CMD_STRING) == 0)
    {
      header_msg(list, my_file, 1);
      if ((*my_file)->tab_instruction[1] != NULL)
	return (0);
    }
  else if (my_strcmp(str, COMMENT_CMD_STRING) == 0)
    { 
      header_msg(list, my_file, 2);
      if ((*my_file)->tab_instruction[1] != NULL)
	return (0);
    }
  else
    syntax_msg(list, my_file, '\0');
  return (1);
}

int	check_order_end_ok(char **name, int is_error,
			   t_list **list, t_my_file **my_file)
{
  my_free_tab(name);
  if (is_error == 1)
    syntax_msg(list, my_file, "\0");
  return (0);
}

int		check_order(t_list **list, t_my_file **my_file)
{
  int		i;
  int		k;
  char		**tab;
  char		**name;
  static int	(*tabfunc[])(char **, t_list**, t_my_file**, char**) = {
    &synt_live, &synt_ld, &synt_st, &synt_add, &synt_sub, &synt_and,
    &synt_or, &synt_xor, &synt_zjmp, &synt_ldi, &synt_sti,
    &synt_fork, &synt_lld, &synt_lldi, &synt_lfork, &synt_aff};

  i = -1;
  name = init_tab(name);
  while ((*my_file)->tab_instruction[++i])
    {
      k = -1;
      while (name[++k] != 0)
	if (my_strcmp(name[k], (*my_file)->tab_instruction[0]) == 0)
	  {
	    if (tabfunc[k]((*my_file)->tab_instruction, list, my_file, name) == 0)
	      return (check_order_end_ok(name, 0, list, my_file));
	    else
	      check_order_end_ok(name, 1, list, my_file);
	  }
    }
  my_free_tab(name);
  return (1);
}

int	syntax_error(t_list **list, t_my_file **my_file)
{
  int	i;
  int	j;
  char	**tab;
 
  i = 0;
  tab = (*my_file)->tab_instruction;
  if (check_command(tab[i], list, my_file) == 0)
    return (0);
  while (tab[++i])
    {
      if (tab[i][0] == ':' || tab[i][1] == ':')
	return (0);
      if (check_command(tab[i], list, my_file) == 0)
	return (0);
      j = 0;
      if (char_cmp(tab[i][0], 'r') == 0 || char_cmp(tab[i][0], '%') == 0)
	while (tab[i][++j])
	  verif_result(list, tab[i][j], tab[i], my_file);
      else
	while (tab[i][++j])
	  verif_result(list, tab[i][j], tab[i], my_file);
    }
  check_order(list, my_file);
  return (0);
}
